<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-header">
      <view class="tab-list">
        <view class="tab-item" :class="{ active: currentTab === 'follow' }" @tap="switchTab('follow')">关注</view>
        <view class="tab-item" :class="{ active: currentTab === 'scenic' }" @tap="switchTab('scenic')">名胜</view>
        <view class="tab-item" :class="{ active: currentTab === 'recommend' }" @tap="switchTab('recommend')">推荐</view>
      </view>
      <view class="header-right">
        <view class="search-icon" @tap="goToSearch">
          <text class="iconfont icon-search"></text>
        </view>
      </view>
    </view>

    <!-- 视频内容 -->
    <swiper class="video-swiper" :current="currentVideoIndex" @change="onSwiperChange" vertical>
      <swiper-item v-for="(item, index) in videoList" :key="index">
        <view class="video-item">
          <!-- 视频播放器 -->
          <video
            :id="'video-' + index"
            class="video-player"
            :src="item.videoUrl"
            :poster="item.coverUrl"
            :show-play-btn="false"
            :controls="false"
            :enable-progress-gesture="false"
            object-fit="cover"
            loop
            @play="onVideoPlay(index)"
            @pause="onVideoPause(index)"
            @ended="onVideoEnd"
            @error="onVideoError"
            @timeupdate="onVideoTimeUpdate($event, index)"
            @tap="toggleVideoPlay(index)"
          ></video>
          
          <!-- 播放按钮 -->
          <view class="play-btn" v-if="!isPlaying || currentVideoIndex !== index" @tap.stop="playVideo(index)">
            <view class="play-btn-inner"></view>
            <text class="iconfont icon-play"></text>
          </view>
          
          <!-- 右侧操作栏 -->
          <view class="action-bar">
            <view class="user-avatar" @tap="goToUserProfile(item.userId)">
              <image :src="item.userAvatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
              <view class="follow-btn">+</view>
            </view>
            <view class="action-item" @tap="likeVideo(item)">
              <view class="icon-wrapper" :class="{'active': item.isLiked}">
                <text class="iconfont" :class="item.isLiked ? 'icon-like-fill' : 'icon-like'"></text>
              </view>
              <text class="count">{{item.likes || 10}}</text>
            </view>
            <view class="action-item" @tap="showComments(item)">
              <view class="icon-wrapper">
                <text class="iconfont icon-comment"></text>
              </view>
              <text class="count">{{item.commentsCount || 2}}</text>
            </view>
            <view class="action-item" @tap="shareVideo(item)">
              <view class="icon-wrapper">
                <text class="iconfont icon-share"></text>
              </view>
              <text class="count">分享</text>
            </view>
            
          </view>
          
          <!-- 底部信息 -->
          <view class="video-info" @tap="goToVideoDetail(item.videoId)">
            <view class="author-name">@{{item.userName || '用户昵称'}}</view>
            <view class="video-desc">{{item.title || '周末旅行 - 山风景'}}</view>
            <view class="video-tags">
              <text class="tag" v-for="(tag, tagIndex) in formatTags(item.tags || '#周末旅行 #山风景')" :key="tagIndex">#{{tag}}</text>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>
    
    <!-- 底部标签栏 -->
  </view>
</template>

<script>
import { getVideoList } from '@/api/video.js';

export default {
  data() {
    return {
      currentTab: 'recommend',
      currentVideoIndex: 0,
      videoList: [],
      isPlaying: false,
      loading: true,
      page: 1,
      size: 5,
      hasNextPage: false,
      videoProgress: []
    }
  },
  onLoad() {
    this.loadVideoList();
  },
  methods: {
    // 加载视频列表
    async loadVideoList() {
      this.loading = true;
      try {
        const res = await getVideoList(this.page, this.size);
        if (res.code === 200) {
          const pageInfo = res.data;
          this.videoList = [...this.videoList, ...pageInfo.list];
          this.hasNextPage = pageInfo.hasNextPage;
          console.log('视频列表数据:', this.videoList);
          
          if (this.videoList.length > 0 && this.currentVideoIndex === 0) {
            // 延迟自动播放第一个视频
            setTimeout(() => {
              this.playVideo(0);
            }, 500);
          }
        } else {
          uni.showToast({
            title: res.errorMessage || '获取视频列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取视频列表出错:', error);
        uni.showToast({
          title: '获取视频列表失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 切换标签
    switchTab(tab) {
      if (tab === 'follow' || tab === 'scenic' || tab === 'recommend') {
        this.currentTab = tab;
        // TODO: 根据不同标签加载不同视频
      } else {
        // 底部标签栏切换
        switch(tab) {
          case 'home':
            // 已在首页，不需要跳转
            break;
          case 'friend':
            uni.navigateTo({
              url: '/pages/friend/index'
            });
            break;
          case 'message':
            uni.navigateTo({
              url: '/pages/message/index'
            });
            break;
          case 'me':
            uni.navigateTo({
              url: '/pages/user/profile'
            });
            break;
        }
      }
    },
    
    // 去搜索页
    goToSearch() {
      uni.navigateTo({
        url: '/pages/search/index'
      });
    },
    
    // 滑动切换视频
    onSwiperChange(e) {
      const oldIndex = this.currentVideoIndex;
      this.currentVideoIndex = e.detail.current;
      
      // 暂停当前视频
      const oldVideo = uni.createVideoContext(`video-${oldIndex}`, this);
      oldVideo.pause();
      this.isPlaying = false;
      
      // 播放新视频
      this.playVideo(this.currentVideoIndex);
      
      // 如果滑动到最后一个视频，加载更多
      if (this.currentVideoIndex === this.videoList.length - 1 && this.hasNextPage) {
        this.page++;
        this.loadVideoList();
      }
    },
    
    // 播放视频
    playVideo(index) {
      // 暂停当前播放的视频
      if (this.isPlaying && this.currentVideoIndex !== index) {
        const oldVideo = uni.createVideoContext(`video-${this.currentVideoIndex}`, this);
        oldVideo.pause();
      }
      
      // 播放指定索引的视频
      const videoContext = uni.createVideoContext(`video-${index}`, this);
      videoContext.play();
      this.isPlaying = true;
      this.currentVideoIndex = index;
    },
    
    // 视频播放事件
    onVideoPlay(index) {
      console.log('视频开始播放:', index);
      this.isPlaying = true;
    },
    
    // 视频播放结束
    onVideoEnd() {
      console.log('视频播放结束');
      this.isPlaying = false;
      
      // 自动播放下一个视频
      if (this.currentVideoIndex < this.videoList.length - 1) {
        this.currentVideoIndex++;
        this.playVideo(this.currentVideoIndex);
      }
    },
    
    // 视频播放错误
    onVideoError(e) {
      console.error('视频播放错误:', e);
      this.isPlaying = false;
      uni.showToast({
        title: '视频播放失败',
        icon: 'none'
      });
    },
    
    // 点赞视频
    likeVideo(item) {
      item.isLiked = !item.isLiked;
      if (item.isLiked) {
        item.likes = (item.likes || 0) + 1;
      } else {
        item.likes = Math.max((item.likes || 0) - 1, 0);
      }
      // TODO: 调用点赞/取消点赞接口
    },
    
    // 显示评论
    showComments(item) {
      // 跳转到视频详情页并显示评论
      uni.navigateTo({
        url: `/pages/video/detail?videoId=${item.videoId}&showComments=true`
      });
    },
    
    // 分享视频
    shareVideo(item) {
      uni.showShareMenu({
        withShareTicket: true
      });
    },
    
    // 去视频详情
    goToVideoDetail(videoId) {
      uni.navigateTo({
        url: `/pages/video/detail?videoId=${videoId}`
      });
    },
    
    // 格式化标签
    formatTags(tagsString) {
      if (!tagsString) return [];
      return tagsString.split(',').map(tag => tag.trim());
    },
    
    // 暂停视频
    onVideoPause(index) {
      const videoContext = uni.createVideoContext(`video-${index}`, this);
      videoContext.pause();
      this.isPlaying = false;
    },
    
    // 更新视频进度
    onVideoTimeUpdate(event, index) {
      this.videoProgress[index] = Math.round((event.detail.currentTime / event.detail.duration) * 100);
    },
    
    // 去用户个人主页
    goToUserProfile(userId) {
      uni.navigateTo({
        url: `/pages/user/profile?userId=${userId}`
      });
    },
    
    // 收藏视频
    collectVideo(item) {
      item.isCollected = !item.isCollected;
      // TODO: 调用收藏/取消收藏接口
    },
    
    // 切换视频播放状态
    toggleVideoPlay(index) {
      if (this.isPlaying && this.currentVideoIndex === index) {
        this.onVideoPause(index);
      } else {
        this.playVideo(index);
      }
    },
    
    // 发布视频
    publishVideo() {
      uni.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back',
        success: (res) => {
          console.log('选择视频成功:', res);
          // 跳转到视频编辑页面
          uni.navigateTo({
            url: `/pages/video/publish?tempFilePath=${res.tempFilePath}&duration=${res.duration}&size=${res.size}&height=${res.height}&width=${res.width}`
          });
        },
        fail: (err) => {
          console.error('选择视频失败:', err);
        }
      });
    }
  }
}
</script>

<style lang="scss">
.container {
  height: 100vh;
  background: #000;
  position: relative;
  overflow: hidden;
}

.nav-header {
  position: fixed;
  top: env(safe-area-inset-top, 0);
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  height: 88rpx;

  .tab-list {
    display: flex;
    align-items: center;
    flex: 1;
    justify-content: center;

    .tab-item {
      font-size: 32rpx;
      color: rgba(255, 255, 255, 0.65);
      margin: 0 40rpx;
      padding: 10rpx 0;
      position: relative;

      &.active {
        color: #fff;
        font-weight: bold;

        &::after {
          content: '';
          position: absolute;
          bottom: -6rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 36rpx;
          height: 6rpx;
          background: #fff;
          border-radius: 3rpx;
        }
      }
    }
  }

  .header-right {
    display: flex;
    align-items: center;

    .search-icon {
      width: 80rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .iconfont {
        font-size: 44rpx;
        color: #fff;
      }
    }
  }
}

.video-swiper {
  height: 100vh;
  width: 100vw;
}

.video-item {
  position: relative;
  height: 100%;
  width: 100%;

  .video-player {
    width: 100%;
    height: 100%;
    background-color: #000;
  }

  .play-btn {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10;
    width: 120rpx;
    height: 120rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .play-btn-inner {
      width: 120rpx;
      height: 120rpx;
      background: rgba(0, 0, 0, 0.3);
      border-radius: 50%;
      position: absolute;
    }
    
    .iconfont {
      font-size: 60rpx;
      color: #fff;
      z-index: 2;
    }
  }

  .action-bar {
    position: absolute;
    right: 24rpx;
    bottom: 240rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    z-index: 10;

    .user-avatar {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 50rpx;
      position: relative;
      
      image {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        border: 4rpx solid #fff;
      }
      
      .follow-btn {
        position: absolute;
        bottom: -16rpx;
        width: 44rpx;
        height: 44rpx;
        background: #FF4040;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #fff;
        border: 2rpx solid #fff;
        font-weight: bold;
      }
    }

    .action-item {
      margin-bottom: 50rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .icon-wrapper {
        width: 84rpx;
        height: 84rpx;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 4rpx;
        
        &.active {
          background: rgba(255, 64, 64, 0.2);
        }
      }
      
      .iconfont {
        font-size: 44rpx;
        color: #fff;
        
        &.icon-like-fill {
          color: #FF4040;
        }
      }
      
      .count {
        font-size: 26rpx;
        color: #fff;
        margin-top: 4rpx;
        text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
      }
    }
    
    .rotate-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      overflow: hidden;
      border: 4rpx solid #fff;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
      
      .record-wrapper {
        width: 100%;
        height: 100%;
        transform: rotate(0deg);
        transition: transform 10s linear infinite;
        
        &.rotate-active {
          animation: rotateRecord 10s linear infinite;
        }
      }
      
      image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .video-info {
    position: absolute;
    left: 24rpx;
    right: 140rpx;
    bottom: 160rpx;
    z-index: 10;
    
    .author-name {
      font-size: 28rpx;
      color: #fff;
      margin-bottom: 12rpx;
      font-weight: 600;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
    }
    
    .video-desc {
      font-size: 28rpx;
      color: #fff;
      margin-bottom: 16rpx;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
      line-height: 1.4;
    }
    
    .video-tags {
      display: flex;
      flex-wrap: wrap;
      
      .tag {
        color: rgba(255, 255, 255, 0.9);
        font-size: 28rpx;
        margin-right: 12rpx;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
      }
    }
  }
}

.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 999;
}

.tab-bar {
  position: fixed;
  bottom: env(safe-area-inset-bottom, 0);
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100rpx;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(10px);
  padding-bottom: env(safe-area-inset-bottom, 0);

  .tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    height: 100%;
    flex: 1;

    .iconfont {
      font-size: 44rpx;
      color: rgba(255, 255, 255, 0.8);
    }

    .tab-text {
      font-size: 22rpx;
      color: rgba(255, 255, 255, 0.8);
      margin-top: 4rpx;
    }

    .badge {
      background: #FF4040;
      border-radius: 16rpx;
      min-width: 32rpx;
      height: 32rpx;
      padding: 0 6rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20rpx;
      color: #fff;
      position: absolute;
      top: 0;
      right: 50%;
      transform: translateX(10rpx);
    }

    .publish-btn {
      width: 72rpx;
      height: 72rpx;
      border-radius: 16rpx;
      background: linear-gradient(to right, #FF4040, #FF6060);
      display: flex;
      align-items: center;
      justify-content: center;
      transform: rotate(45deg);
      margin-bottom: 8rpx;

      .iconfont {
        font-size: 40rpx;
        color: #fff;
        transform: rotate(-45deg);
      }
    }
  }
}

@keyframes rotateRecord {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 安全区适配 */
@supports (padding-top: env(safe-area-inset-top)) {
  .nav-header {
    padding-top: env(safe-area-inset-top);
    height: calc(88rpx + env(safe-area-inset-top));
  }
  
  .tab-bar {
    padding-bottom: env(safe-area-inset-bottom);
    height: calc(100rpx + env(safe-area-inset-bottom));
  }
  
  .video-swiper {
    height: 100vh;
  }
}
</style> 